#pragma GCC optimize(2)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <vector>

using namespace std;
using LL = long long;
const int N = 410;

int n, m;
int g[N][N];
int psum[N][N];
string s;

int f(int x1, int y1, int x2, int y2){
    return psum[x2][y2] - psum[x2][y1 - 1] - psum[x1 - 1][y2] + psum[x1 - 1][y1 - 1]; 
}

int calc(int x1, int y1, int x2, int y2){
    int k1 = f(x1 + 1, y1 + 1, x2 - 1, y2 - 1);
    int k2 = y2 - y1 - 1 - f(x2, y1 + 1, x2, y2 - 1);
    int k3 = y2 - y1 - 1 - f(x1, y1 + 1, x1, y2 - 1);
    int k4 = x2 - x1 - 1 - f(x1 + 1, y2, x2 - 1, y2);
    int k5 = x2 - x1 - 1 - f(x1 + 1, y1, x2 - 1, y1);
    return k1 + k2 + k3 + k4 + k5;
}


int calc1(int x1, int y1, int x2, int y2){
    int k1 = f(x1 + 1, y1 + 1, x2 - 1, y2 - 1);
    int k2 = y2 - y1 - 1 - f(x2, y1 + 1, x2, y2 - 1);
    int k3 = y2 - y1 - 1 - f(x1, y1 + 1, x1, y2 - 1);
    int k4 = x2 - x1 - 1 - f(x1 + 1, y2, x2 - 1, y2);
    int k5 = x2 - x1 - 1 - f(x1 + 1, y1, x2 - 1, y1);

    return k1 + k2 + k3 + k5;
}


void solve(){
    cin >> n >> m;
    for(int i = 1; i <= n; i ++){
        cin >> s;
        for(int j = 1; j <= m; j ++){
            g[i][j] = (s[j - 1] - '0');
        }
    }

    for(int i = 1; i <= n; i ++){
        for(int j = 1; j <= m; j ++){
            psum[i][j] = g[i][j] + psum[i - 1][j] + psum[i][j - 1] - psum[i - 1][j - 1];
        }
    }

    int res = 16;




    for(int i = 1; i + 4 <= n; i ++){
        for(int j = 1; j + 3 <= m; j ++){
            for(int i1 = i + 4; i1 <= n; i1 ++){
                for(int j1 = j + 3; j1 <= m; j1 ++){
                    if(calc1(i, j, i1, j1) >= res) break;
                    res = min(res, calc(i, j, i1, j1));
                }
            }
        }
    }

    cout << res << '\n';
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while(T--){
        solve();
    }



    return 0;
}